package org.example.minio;

import cn.hutool.core.io.FileUtil;
import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 李国树
 * @version 1.0
 * @Desc
 * @date 2023/11/18 10:41
 */
@Component
public class MinioService {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    public String upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        fileName = UUID.randomUUID().toString() + "." + FileUtil.extName(fileName);
        boolean exist = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(bucketName)
                .build());
        if (!exist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        InputStream inputStream = file.getInputStream();
        // 上传到minio服务器
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(inputStream, -1L, 10485760L)
                .build());
        return fileName;
    }

    public void downloadFile(String fileName, HttpServletResponse response) throws Exception {
        try (InputStream inputStream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .build())) {
            // Read data from stream
            byte[] bytes = IOUtils.toByteArray(inputStream);
            response.getOutputStream().write(bytes);
            //FileUtils.writeByteArrayToFile(new File("C:\\Users\\pc\\Desktop\\" + fileName), bytes);
            IOUtils.closeQuietly(inputStream);
        }
    }
}

 
